
package ru.surfstudio.webservicetemplate.activity;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import ru.surfstudio.webservicetemplate.R;
import ru.surfstudio.webservicetemplate.dto.GoogleSearchResultDto;
import ru.surfstudio.webservicetemplate.service.HttpService;
import ru.surfstudio.webservicetemplate.task.GoogleSearchTask;
import ru.surfstudio.webservicetemplate.util.DialogUtil;
import ru.surfstudio.webservicetemplate.util.UiUtil;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.google.android.apps.iosched.util.DetachableResultReceiver;

public class GoogleSearchActivity extends Activity {

    private static final String TAG = GoogleSearchActivity.class.getSimpleName();

    private static final String STATE_RESULT_LIST = "STATE_RESULT_LIST";

    private static final int DIALOG_SEARCH = 0x0;

    private EditText searchEditText;

    private ListView listView;

    private ArrayAdapter<GoogleSearchResultDto> adapter;
    
    private List<GoogleSearchResultDto> googleSearchResultList;

    private ActivityState state;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate");
        setContentView(R.layout.google_search);

        searchEditText = (EditText)findViewById(R.id.google_search_edit_text);
        googleSearchResultList = new ArrayList<GoogleSearchResultDto>();
        adapter = new SearchResultAdapter(this, googleSearchResultList);
        listView = (ListView)findViewById(R.id.google_search_list_view);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                GoogleSearchResultDto item = googleSearchResultList.get(position);
                // Just open browser
                Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(item.url));
                startActivity(i);
            }
        });

        state = new ActivityState();
        if (savedInstanceState != null) {
        	googleSearchResultList = (List<GoogleSearchResultDto>)savedInstanceState
            		.getSerializable(STATE_RESULT_LIST);
        }
        state.attach(this);
    }
    
    @Override
    protected void onDestroy() {
    	super.onDestroy();
    	Log.d(TAG, "onDestroy");
    	state.detach();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        Log.d(TAG, "onSaveInstanceState");
        outState.putSerializable(STATE_RESULT_LIST, (Serializable)googleSearchResultList);
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case DIALOG_SEARCH:
            	return DialogUtil.createCancelableProgressDialog(this, R.string.google_search_dialog_text);
        }
        return super.onCreateDialog(id);
    }

    /** Search button click event */
    public void onSearchButtonClick(View view) {
        String searchString = searchEditText.getText().toString();
        if (searchString == null || searchString.equals("")) {
            UiUtil.showToast(this, R.string.google_search_empty_text_error);
        } else {
            Intent intent = new Intent(this, HttpService.class);
            intent.putExtra(HttpService.EXTRA_STATUS_RECEIVER, state.receiver);
            intent.putExtra(HttpService.EXTRA_HTTP_TASK, new GoogleSearchTask(searchString));
            startService(intent);
        }
    }

    private class SearchResultAdapter extends ArrayAdapter<GoogleSearchResultDto> {

        public SearchResultAdapter(Context context, List<GoogleSearchResultDto> list) {
            super(context, android.R.layout.simple_list_item_1, list);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = new TextView(getContext());
            }
            GoogleSearchResultDto item = getItem(position);
            if (item != null) {
                ((TextView)convertView).setText(Html.fromHtml(item.title));
            }
            return convertView;
        }
    }

    private class SearchRequestReceiver implements DetachableResultReceiver.Receiver {

        @Override
        public void onReceiveResult(int resultCode, Bundle resultData) {
            switch (resultCode) {
                case HttpService.STATUS_RUNNING: {
                    showDialog(DIALOG_SEARCH);
                    break;
                }
                case HttpService.STATUS_FINISHED: {
                    dismissDialog(DIALOG_SEARCH);
                    List<GoogleSearchResultDto> resultList = (List<GoogleSearchResultDto>)resultData
                            .getSerializable(HttpService.EXTRA_RESULT);
                    onSearchRequestFinished(resultList);
                    break;
                }
                case HttpService.STATUS_ERROR: {
                    dismissDialog(DIALOG_SEARCH);
                    int errorCode = resultData.getInt(HttpService.EXTRA_ERROR_CODE);
                    switch (errorCode) {
                        case HttpService.ERROR_CODE_BUSINESS:
                            // Process some business exception here...
                            break;
                        case HttpService.ERROR_CODE_TRANSPORT:
                            String errorText = getString(R.string.google_search_transport_error);
                            UiUtil.showToast(GoogleSearchActivity.this, errorText, true);
                    }
                }
            }
        }
    }
    
    private void onSearchRequestFinished(List<GoogleSearchResultDto> result) {
    	googleSearchResultList.clear();
        googleSearchResultList.addAll(result);
        adapter.notifyDataSetChanged();
    }

    /** Activity state */
    private static class ActivityState {

        public DetachableResultReceiver receiver;

        public ActivityState() {
        	// Attaching receiver to this context
            receiver = new DetachableResultReceiver(new Handler());
        }
        
        public void attach(GoogleSearchActivity activity) {
        	receiver.setReceiver(activity.new SearchRequestReceiver());
		}

		public void detach() {
			receiver.clearReceiver();
		}
    }
}